<!--
  生成结算单对话框组件
  @description 生成结算单的表单对话框
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="t('settle.settleOrder.generate')" width="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('settle.settleOrder.merchantNo')" prop="merchantNo">
        <el-select
          v-model="formData.merchantNo"
          :placeholder="t('settle.settleOrder.rules.merchantNoRequired')"
          style="width: 100%"
          filterable
          remote
          :remote-method="searchMerchants"
          :loading="merchantLoading"
          @change="handleMerchantChange"
        >
          <el-option
            v-for="merchant in merchantOptions"
            :key="merchant.merchantNo"
            :label="`${merchant.merchantNo} - ${merchant.merchantName}`"
            :value="merchant.merchantNo"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('settle.settleOrder.settleCycle')" prop="settleCycle">
        <el-select
          v-model="formData.settleCycle"
          :placeholder="t('settle.settleOrder.rules.settleCycleRequired')"
          style="width: 100%"
        >
          <el-option
            v-for="(label, value) in settleCycleOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('settle.settleOrder.settleDate')" prop="settleDate">
        <el-date-picker
          v-model="formData.settleDate"
          type="date"
          :placeholder="t('settle.settleOrder.rules.settleDateRequired')"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item :label="t('settle.settleOrder.dateRange')" prop="dateRange">
        <el-date-picker
          v-model="formData.dateRange"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('settle.common.startTime')"
          :end-placeholder="t('settle.common.endTime')"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 预览信息 -->
      <el-card v-if="previewData" class="preview-card">
        <template #header>
          <span>{{ t('settle.settleOrder.preview') }}</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item :label="t('settle.settleOrder.orderCount')">
            {{ previewData.orderCount }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.totalAmount')">
            ¥{{ (previewData.totalAmount / 100).toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.feeAmount')">
            ¥{{ (previewData.feeAmount / 100).toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.settleAmount')">
            <span class="settle-amount">¥{{ (previewData.settleAmount / 100).toFixed(2) }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-form-item :label="t('settle.common.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :placeholder="t('settle.common.pleaseInput') + t('settle.common.remark')"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handlePreview" :disabled="!canPreview" :loading="previewLoading">
        {{ t('settle.settleOrder.preview') }}
      </el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading || !previewData">
        {{ t('settle.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('settle.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { createSettleOrderApi, getSettleOrderApi } from '@/api/settle/settleOrder'
import { getMerchantListApi } from '@/api/settle/merchant'
import type {
  GenerateSettleOrderReqVO,
  PreviewSettleOrderReqVO,
  PreviewSettleOrderVO,
  MerchantVO
} from '@/api/settle/types'
import { SettleCycleEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'GenerateSettleDialog' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const formLoading = ref(false)
const previewLoading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formData = ref<GenerateSettleOrderReqVO>({
  merchantNo: '',
  settleCycle: SettleCycleEnum.DAILY,
  settleDate: '',
  dateRange: [],
  remark: ''
})

// 商户选项
const merchantOptions = ref<MerchantVO[]>([])
const merchantLoading = ref(false)

// 预览数据
const previewData = ref<PreviewSettleOrderVO>()

// 选项数据
const settleCycleOptions = {
  [SettleCycleEnum.DAILY]: t('settle.settleOrder.settleCycles.daily'),
  [SettleCycleEnum.WEEKLY]: t('settle.settleOrder.settleCycles.weekly'),
  [SettleCycleEnum.MONTHLY]: t('settle.settleOrder.settleCycles.monthly')
}

// 表单校验规则
const formRules = reactive<FormRules>({
  merchantNo: [
    { required: true, message: t('settle.settleOrder.rules.merchantNoRequired'), trigger: 'change' }
  ],
  settleCycle: [
    {
      required: true,
      message: t('settle.settleOrder.rules.settleCycleRequired'),
      trigger: 'change'
    }
  ],
  settleDate: [
    { required: true, message: t('settle.settleOrder.rules.settleDateRequired'), trigger: 'change' }
  ],
  dateRange: [
    { required: true, message: t('settle.settleOrder.rules.dateRangeRequired'), trigger: 'change' }
  ]
})

// 计算属性
const canPreview = computed(() => {
  return (
    formData.value.merchantNo &&
    formData.value.settleCycle !== undefined &&
    formData.value.settleDate &&
    formData.value.dateRange &&
    formData.value.dateRange.length === 2
  )
})

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开弹窗
 */
const open = async () => {
  dialogVisible.value = true
  resetForm()

  // 加载商户列表
  await loadMerchants()
}

/**
 * 提交表单
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  if (!previewData.value) {
    ElMessage.warning(t('settle.settleOrder.tips.previewFirst'))
    return
  }

  formLoading.value = true
  try {
    await createSettleOrderApi(formData.value)
    ElMessage.success(t('settle.settleOrder.tips.generateSuccess'))
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('生成结算单失败:', error)
  } finally {
    formLoading.value = false
  }
}

/**
 * 预览结算单
 */
const handlePreview = async () => {
  if (!canPreview.value) {
    ElMessage.warning(t('settle.settleOrder.tips.fillRequired'))
    return
  }

  previewLoading.value = true
  try {
    const previewReq: PreviewSettleOrderReqVO = {
      merchantNo: formData.value.merchantNo,
      settleCycle: formData.value.settleCycle,
      dateRange: formData.value.dateRange
    }

    const data = await getSettleOrderApi(previewReq)
    previewData.value = data

    if (data.orderCount === 0) {
      ElMessage.warning(t('settle.settleOrder.tips.noOrdersToSettle'))
    }
  } catch (error) {
    console.error('预览结算单失败:', error)
  } finally {
    previewLoading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    merchantNo: '',
    settleCycle: SettleCycleEnum.DAILY,
    settleDate: '',
    dateRange: [],
    remark: ''
  }
  previewData.value = undefined
  formRef.value?.resetFields()
}

/**
 * 商户变化处理
 */
const handleMerchantChange = () => {
  // 清空预览数据
  previewData.value = undefined
}

/**
 * 加载商户列表
 */
const loadMerchants = async () => {
  try {
    merchantLoading.value = true
    const data = await getMerchantListApi(1) // 只获取审核通过的商户
    merchantOptions.value = data
  } catch (error) {
    console.error('加载商户列表失败:', error)
  } finally {
    merchantLoading.value = false
  }
}

/**
 * 搜索商户
 */
const searchMerchants = async (query: string) => {
  if (query) {
    // 这里可以实现远程搜索逻辑
    await loadMerchants()
  }
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.preview-card {
  margin: 20px 0;
}

.settle-amount {
  color: #67c23a;
  font-weight: bold;
  font-size: 16px;
}
</style>
